package cn.xw.mq.producer;

import cn.xw.config.RabbitMQConfig;
import cn.xw.entity.MessageSendDTO;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-16 15:01
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TestProducer {

    private final RabbitTemplate rabbitTemplate;

    /***
     * 生产者方法
     * @param msg 消息
     */
    public void producerSendMsgDelay(MessageSendDTO msg) {
        //消息转换为JSON格式并转为字节数组
        byte[] bytes = JSONObject.toJSONString(msg).getBytes(StandardCharsets.UTF_8);
        //其它的一些信息，用来回调用处
        CorrelationData correlationData = new CorrelationData();
        //设置id信息，其实默认就是UUID，我们其实可以根据自己设置指定ID信息
        //correlationData.setId(String.valueOf(UUID.randomUUID()));

        //发送消息（不可以成功发送,路由key不存在）
        rabbitTemplate.convertAndSend(RabbitMQConfig.CONFIRM_EXCHANGE,
                RabbitMQConfig.CONFIRM_ROUTING_KEY + "test", bytes, correlationData);
    }
}
